<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 车辆
 *
 * @icon fa fa-car
 */
class Car extends Backend
{

    /**
     * Car模型对象
     * @var \app\admin\model\Car
     */
    protected $model = null;
    protected $noNeedRight = ['export'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Car;
        $this->view->assign("isInstallList", $this->model->getIsInstallList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDelList", $this->model->getIsDelList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $admininfo=$this->auth->getUserInfo();
            $where_admin=[];
            if($admininfo['store_id'])
            {
                $where_admin['store_id']=$admininfo['store_id'];
            }
            $list = $this->model
                    ->with(['store','discharging'])
                    ->where($where)
                    ->where($where_admin)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('store')->visible(['store_name']);
				$row->getRelation('discharging')->visible(['name']);
            
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if (false === $this->request->isPost()) {
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //判断手机号是否存在
            $isexist=$this->model->where(['plate_number'=>$params['plate_number'],'is_del'=>'0'])->count();
            if($isexist)
            {
                $this->error(__('车牌号已存在'));
            }

            $admininfo=$this->auth->getUserInfo();
            if($admininfo['store_id']>0)
            {
                $params['store_id']=$admininfo['store_id'];
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['imagelist']=explode(',',$row['images']);
            $this->view->assign('row', $row);
            $admininfo=$this->auth->getUserInfo();
            $this->assign('admininfo',$admininfo);
            $this->assign('store_id',$admininfo['store_id']);

            $change_info=db('change_log')->where(['type'=>'2','change_id'=>$ids])->order('id desc')->find();
            $change_images=[];
            if($change_info)
            {
                $change_images=$change_info['change_images'];
                if($change_images)
                {
                    $change_images=explode(',',$change_images);
                }
            }
            
            $this->assign('change_images',$change_images);
            $this->assign('change_info',$change_info);
            
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $admininfo=$this->auth->getUserInfo();
            $store_id=$admininfo['store_id'];
            if(isset($params['num']))
            {
                //判断编号是否存在
                $isexist=$this->model->where(['is_del'=>'0','num'=>$params['num'],'id'=>['neq',$ids]])->count();
                if($isexist)
                {
                    $this->error(__('编号已存在'));
                }
            }

            $isexist=$this->model->where(['is_del'=>'0','plate_number'=>$params['plate_number'],'id'=>['neq',$ids]])->count();
            if($isexist)
            {
                $this->error(__('车牌号已存在'));
            }
            
            //如果信息是正在审核中的，禁止修改
            if(($row['status']=='1' || $row['status']=='2') && $store_id>0)
            {
                $this->error(__('审核中不可修改', ''));
            }
            if($store_id==0)
            {
                if(isset($params['status'])=='3' && $row['status']=='2')
                {
                    //通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'2','change_id'=>$ids,'status'=>'2'])->find();
                    if(isset($change_info['change_images']) && $change_info['change_images'])
                    {
                        $params['images']=$row['images'].','.$change_info['change_images'];
                    }
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'3']);

                    $filename=$this->create_ewm($ids);
                    $params['qrcode']=$filename;
                    // var_dump($ids);
                    // var_dump($params['qrcode']);die;
    
                }
                if(isset($params['status'])=='4' && $row['status']=='2')
                {
                    //未通过,如果有申请中的变更记录，需要更改状态
                    $change_info=db('change_log')->where(['type'=>'2','change_id'=>$ids,'status'=>'2'])->find();
                    db('change_log')->where(['id'=>$change_info['id']])->update(['status'=>'4']);
                }
            }
            else
            {
                $params['status']='2';
            }
            
            if(isset($params['change_title']))
            {
                $change_title=$params['change_title'];
                $change_images=$params['change_images'];
                unset($params['change_title']);
                unset($params['change_images']);
                
                $result_data['type']='2';
                $result_data['change_id']=$row['id'];
                $result_data['change_title']=$change_title;
                $result_data['change_images']=$change_images;
                $result_data['add_time']=time();
                $change_result=db('change_log')->insert($result_data);
            }
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function create_ewm($value){
        //生成二维码
        $matrixPointSize=24;
        vendor('phpqrcode');//引入类库
        $errorCorrectionLevel = 'L';  //容错级别
        // 判断是否有这个文件夹  没有的话就创建一个
        if(!is_dir("uploads/qecodecar")){
            // 创建文件加
            mkdir("uploads/qecodecar");
        }
        //设置二维码文件名
        $name=$value;
        $filename = "uploads/qecodecar/".$name.".png";
        if(file_exists("./".$filename)){
            return '/'.$filename;
            // return 1;
        }
        //生成二维码
        \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize, 2);

        return '/'.$filename;
    }
    
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        $list = $this->model->where($pk, 'in', $ids)->select();
     
        foreach ($list as $key => $value) {
            # code...
            if(($value['status']=='1' || $value['status']=='2'))
            {
                $this->error(__($value['plate_number'].'正在审核中不可删除', ''));
            }
        }
        $count = 0;
        Db::startTrans();
        try {
            
            $res=$this->model->where($pk, 'in', $ids)->update(['is_del'=>'1','status'=>'2']);
            $idsarr=explode(',',$ids);
            // var_dump($idsarr);die;
            foreach ($idsarr as $key => $value) {
                # code...
                $change_title='项目删除';
                
                $result_data['type']='2';
                $result_data['change_id']=$value;
                $result_data['change_title']=$change_title;
                $result_data['add_time']=time();
                $insertall[]=$result_data;
                
            }
            if($insertall)
            {
                $change_result=db('change_log')->insertAll($insertall);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    //导出
    public function export()
    {
        $search = $this->request->post('search');
        $ids = $this->request->post('ids');
        $filter = $this->request->post('filter');
        $op = $this->request->post('op');
        $columns = $this->request->post('columns');
        $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();


        $admininfo=$this->auth->getUserInfo();
        $where_admin=[];
        if($admininfo['store_id'])
        {
            $where_admin['store_id']=$admininfo['store_id'];
        }
        $count=$this->model               
                ->where($where)
                ->where($where_admin)
                ->count();
        // var_dump($count);die;
        $p=$offset/$limit;
        $p=$p+1;
        $list = $this->model      
                ->alias('c')->join('discharging d','c.discharging_id=d.id','left')     
                ->join('store s','c.store_id=s.id','left') 
                ->where($where)
                ->where($where_admin)
                ->order('store_id', 'asc')
                ->field('c.*,s.store_name,s.zz_num,d.name as discharging_name')
                ->select();
     
   
            vendor('PHPExcel.PHPExcel');
            //添加标题到数组头部
            $file_name = '车辆列表' . date('Y-m-d_His') . '.xls';
            $PHPExcel = new \PHPExcel();
            // print_r($PHPExcel);die;
            
            $PHPSheet = $PHPExcel->getActiveSheet();
            // 设置A列的宽度为20
            //    $PHPSheet->getColumnDimension('A')->setWidth(30);
           // 设置B列的宽度为30
        //    $PHPSheet->getColumnDimension('B')->setWidth(30);
        //    $PHPSheet->getColumnDimension('C')->setWidth(20);
        //    $PHPSheet->getColumnDimension('D')->setWidth(20);
        //    $PHPSheet->getColumnDimension('E')->setWidth(20);
           $PHPSheet->getColumnDimension('F')->setWidth(20);
           $PHPSheet->getColumnDimension('G')->setWidth(20);
           $PHPSheet->getColumnDimension('K')->setWidth(30);
           $PHPSheet->getColumnDimension('O')->setWidth(30);
           $PHPSheet->getColumnDimension('P')->setWidth(30);
           $PHPSheet->getColumnDimension('Q')->setWidth(30);
           $PHPSheet->getColumnDimension('L')->setWidth(30);
           $PHPSheet->getColumnDimension('M')->setWidth(20);
            $PHPSheet->setTitle("表格一");
            
           
  
            
            $PHPSheet->setCellValue("A1", "序号");
            $PHPSheet->setCellValue("B1", "所属市名称");
            $PHPSheet->setCellValue("C1", "所属市代码");
            $PHPSheet->setCellValue("D1", "所属区县名称");
            $PHPSheet->setCellValue("E1", "所属区县代码");
            $PHPSheet->setCellValue("F1", "渣土运输公司");
            $PHPSheet->setCellValue("G1", "排放阶段");
            $PHPSheet->setCellValue("H1", "总重量（吨）");
            $PHPSheet->setCellValue("I1", "否安装跟踪器");
            $PHPSheet->setCellValue("J1", "车牌号");
            $PHPSheet->setCellValue("K1", "统一社会信用代码");
            $PHPSheet->setCellValue("L1", "上报时间");
            $PHPSheet->setCellValue("M1", "更新时间");
            $PHPSheet->setCellValue("N1", "是否在用");
            $PHPSheet->setCellValue("O1", "车牌颜色");
            $PHPSheet->setCellValue("P1", "燃料种类");
            $PHPSheet->setCellValue("Q1", "品牌型号");
            $PHPSheet->setCellValue("R1", "核定载重（吨）");
            $i = 2;
           // dump($res);die;
            $lastStoreName = '';
            $startRow = 2;  
            $styleArray = array(  
                'alignment' => array(  
                    'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,  
                    'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,  
                    'wrap' => true, // 设置自动换行 
                ),  
            );  
             
            foreach ($list as $keys => $value) {    
                $values['add_time']=date('Y-m-d H:i:s',$value['add_time']);
                $values['edit_time']=empty($value['edit_time'])?'':date('Y-m-d H:i:s',$value['edit_time']);
                $PHPSheet->setCellValue('A' . $i, '' . $keys+1);
                $PHPSheet->setCellValue('B' . $i, '' . '定州市');
                $PHPSheet->setCellValue('C' . $i, '' . '130682');
                $PHPSheet->setCellValue('D' . $i, '' . '定州市');
                $PHPSheet->setCellValue('E' . $i, '' . '130682');
                
                $currentStoreName = $value['store_id'];  
                if ($currentStoreName != $lastStoreName && !empty($lastStoreName)) {  
                    // 如果当前store_name和上一个不同，并且上一个不是空的，则合并上一个的单元格  
                    $PHPSheet->mergeCells('F' . $startRow . ':' . 'F' . ($i - 1));  

                    
                    $PHPSheet->getStyle('F' . $startRow)->applyFromArray($styleArray); 


                    $startRow = $i; // 重置起始行  
                }  
                $lastStoreName = $currentStoreName; 
                $PHPSheet->setCellValue('F' . $i, '' . $value['store_name']);
                $PHPSheet->setCellValue('G' . $i, '' . $value['discharging_name']);
                $PHPSheet->setCellValue('H' . $i, '' . $value['total_weight']);
                if($value['is_install']==2)
                {
                    $value['is_install']=0;
                }
                $PHPSheet->setCellValue('I' . $i, '' . $value['is_install']);
                $PHPSheet->setCellValue('J' . $i, '' . $value['plate_number']);
                $PHPSheet->setCellValue('K' . $i, '' . $value['zz_num'].' ');
                $PHPSheet->setCellValue('L' . $i, '' . $values['add_time']);
                $PHPSheet->setCellValue('M' . $i, '' . $values['edit_time']);
                $PHPSheet->setCellValue('N' . $i, '' . $value['is_del']);
                $PHPSheet->setCellValue('O' . $i, '' . $value['plate_color']);
                $PHPSheet->setCellValue('P' . $i, '' . $value['fuel_type']);
                $PHPSheet->setCellValue('Q' . $i, '' . $value['brand_model']);
                $PHPSheet->setCellValue('R' . $i, '' . $value['approved_weight']);
                for ($col = 'A'; $col <= 'S'; $col++) {  
                    // 设置单元格的自动换行样式  
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                    $PHPSheet->getStyle($col . $i)->applyFromArray($styleArray); 
                }  
                
                $i++;
            }
            // 最后，检查最后一个store_name的单元格是否需要合并（如果列表不以不同的store_name结束）  
            if ($lastStoreName != '') {  
                $PHPSheet->mergeCells('F' . $startRow . ':' . 'F' . ($i - 1));  
                $PHPSheet->getStyle('F' . $startRow)->applyFromArray($styleArray); 
            }  
            for ($col = 'A'; $col <= 'S'; $col++) {  
                // 设置单元格的自动换行样式  
                $PHPSheet->getStyle($col . 1)->applyFromArray($styleArray); 
            } 
           
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
            header('Content-Disposition: attachment;filename=' . $file_name);
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output");
   
       
    }

}
